package com.yb;

/**
 * 典型数组处理算法
 */
public class ArrayWorks {
    //找出数组中最大元素
    public static int findMaxOfArray(int[] a) {
        int max = a[0];
        for (int i = 1; i < a.length; i++) {
            if (a[i] > max) {
                max = a[i];
            }
        }
        return max;
    }

    //计算数组元素的平均值
    public static double averageOfArray(int[] a) {
        int N = a.length;
        double sum = 0.0;
        for (int i = 0; i < N; i++) {
            sum += a[i];
        }
        return sum / N;
    }

    //复制数组
    public static int[] copyOfArray(int[] a) {
        int N = a.length;
        int[] b = new int[N];
        for (int i = 0; i < N; i++) {
            b[i] = a[i];
        }
        return b;
    }

    //颠倒数组元素的顺序
    public static int[] reverse(int[] a) {
        int N = a.length;
        for (int i = 0; i < N / 2; i++) {
            int temp = a[i];
            a[i] = a[N - 1 - i];
            a[N - 1 - i] = temp;
        }
        return a;
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        System.out.println(findMaxOfArray(a));
        System.out.println(averageOfArray(a));
        System.out.println(toString(copyOfArray(a)));
        System.out.println(toString(reverse(a)));
    }

    public static String toString(int[] a) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < a.length; i++) {
            sb.append(",").append(a[i]);
        }
        return sb.length() == 0 ? "" : sb.toString().substring(1);
    }
}
